package test;

import bean.User;

import java.sql.*;

public class Link_db {

    public static String query(User user) throws ClassNotFoundException, SQLException {
        //1.加载并注册数据库驱动
        Class.forName("com.mysql.jdbc.Driver");
        // 2.获取数据库链接
        String url = "jdbc:mysql://localhost:3306/blog?serverTimezone=GMT%2B8";
        String user1 = "root";
        String password = "123456";
        Connection conn = DriverManager.getConnection(url, user1, password);
        Statement statement = conn.createStatement();
        // 准备sql语句
        String sql = "select * from user";
        // 4. 执行sql语
        ResultSet resultSet = statement.executeQuery(sql);
        System.out.println("id | username | password");
        int flag = 0;
        // 5. 遍历输出结果集
        while (resultSet.next()) {
            int id = resultSet.getInt("id");
            String username = resultSet.getString("username");
            if(username.equals(user.getName())){
                flag = 1;
                if(resultSet.getString("password").equals(user.getPassword())){
                    System.out.println("1");
                    return "登录成功";
                }else {
                    return "密码错误";
                }
            }
            String password1 = resultSet.getString("password");
            System.out.println(id + " | " + username + " | " + password1 + " | ");
        }
        if(flag == 0 ){
            return "用户名不存在";
        }else {
            return "用户名存在";
        }
    }
}


